package com.dcy.znoa.service.publiz.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.dcy.znoa.dao.user.OperDao;
import com.dcy.znoa.domain.Oper;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dcy.znoa.common.exception.BusinessException;
import com.dcy.znoa.common.util.pojo.JsonCommon;
import com.dcy.znoa.common.util.pojo.JsonForList;
import com.dcy.znoa.controller.attendance.model.apply.SelectApplyModel;
import com.dcy.znoa.controller.publiz.model.SelectBaseModel;
import com.dcy.znoa.controller.publiz.model.message.QueryEntityModel;
import com.dcy.znoa.controller.publiz.model.message.SelectMessageModel;
import com.dcy.znoa.controller.publiz.model.message.SelectMsgGroupModel;
import com.dcy.znoa.dao.attendance.ApplyDao;
import com.dcy.znoa.dao.attendance.AttRealRecordDao;
import com.dcy.znoa.dao.conference.OperGuestDao;
import com.dcy.znoa.dao.publiz.CompanyDao;
import com.dcy.znoa.dao.publiz.MessNoticeDao;
import com.dcy.znoa.dao.publiz.MessageDao;
import com.dcy.znoa.domain.attendance.Apply;
import com.dcy.znoa.domain.attendance.AttRealRecord;
import com.dcy.znoa.domain.publiz.MessNotice;
import com.dcy.znoa.domain.publiz.Message;
import com.dcy.znoa.domain.sys.MsgItemVo;
import com.dcy.znoa.service.attendance.ApplyService;
import com.dcy.znoa.service.conference.ConferenceService;
import com.dcy.znoa.service.publiz.MessNoticeService;
import com.dcy.znoa.service.publiz.MessageService;

import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
public class MessageServiceImpl implements MessageService {

    @Autowired
    MessageDao messageDao;
    @Autowired
    CompanyDao companyDao;
    @Autowired
    MessNoticeDao messNoticeDao;
    @Resource
    ApplyService applyService;
    @Resource
    MessNoticeService messNoticeService;
    @Autowired
	OperGuestDao operGuestDao;
    @Resource
    ConferenceService  conferenceService;
    @Resource
    AttRealRecordDao attRealRecordDao;
    @Resource
    ApplyDao applyDao;
    @Resource
    OperDao operDao;

    @Override
    public JsonForList selectList(SelectMessageModel model) throws InvocationTargetException, IllegalAccessException {
        EntityWrapper<Message> ew = new EntityWrapper<>();
        Message cp = new Message();
        BeanUtils.copyProperties(cp, model);
        cp.setMessTitle(null);
        ew.setEntity(cp);
        ew.like("message_title", model.getMessTitle());
        Integer total = SelectBaseModel.PageFill(model, ew, messageDao);//加入分页参数
//        List<Message> list = messageDao.selectListMapper(ew);
        List<Message> list;
        if (model.getPageNum() > 0 && model.getPageSize() > 0) {
            RowBounds rowBounds = new RowBounds(model.getPageNum() - 1, model.getPageSize());
            list = messageDao.selectPage(rowBounds, ew);
        } else {
            list = messageDao.selectList(ew);
        }
        return new JsonForList(list, total);
    }

    @Override
    public Page selectListMapper(SelectMessageModel model) throws InvocationTargetException, IllegalAccessException {
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<Message> list = messageDao.selectListMapper(model, page);
        page.setRecords(list);
        return page;
    }

    @Override
    public MsgItemVo selectGroupItemByOperId(SelectMsgGroupModel model) {
        return messageDao.selectGroupItemByOperId(model);
    }


    @Override
    public JsonForList selectReadListByType(SelectMessageModel model) {
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<Message> list = messageDao.selectReadListByType(model, page);
        return new JsonForList(list, page.getTotal());
//        return messageDao.selectReadListByType(model);
    }

    @Override
    public JsonForList selectUnReadListByType(SelectMessageModel model) {
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<Message> list = messageDao.selectUnReadListByType(model, page);
        return new JsonForList(list, page.getTotal());
    }

    @Override
    public JsonForList selectListByType(SelectMessageModel model) {
        Page page = new Page(model.getPageNum(), model.getPageSize());
        List<Message> list = messageDao.selectListByType(model, page);
        return new JsonForList(list, page.getTotal());
    }

    @Override
    public Integer readMsg(Long operId, String entityTbl, Long entityId) {
        //查询message中有没有数据
        List<Message> list = messageDao.selectList(new EntityWrapper<Message>().eq("entity_tbl", entityTbl).eq("entity_id", entityId));
        if (list.isEmpty()) {
            return 0;
        }
        Date now = new Date();
        boolean flag = false;
        //查询有没有对应的数据 mess_notice中
        for (Message message : list) {//由于数据一般不会多，所以就用循环了
            List<MessNotice> mnlist = messNoticeDao.selectList(new EntityWrapper<MessNotice>().eq("mess_id", message.getMessId()).eq("receive_oper_id", operId).isNull("receive_time"));
            if (mnlist.isEmpty()) {
                continue;
            }
            for (MessNotice messNotice : mnlist) {
                messNotice.setReceiveTime(now);
                messNoticeDao.updateById(messNotice);
                flag = true;
            }
        }
        if (flag == true) {
            return 1;
        }
        return 0;
    }

    @Override
    public JsonCommon insert(Message var1) {
        Integer result = messageDao.insert(var1);
        if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.INSERT_ERROR_CODE);
        }
        return new JsonCommon(var1);
    }

    @Override
    public JsonCommon updateById(Message var1) {
        Integer result = messageDao.updateById(var1);
        if (result == null || result <= 0) {
            return new JsonCommon(JsonCommon.INSERT_ERROR_CODE);
        }
        return new JsonCommon(var1);
    }

    @Override
    public Object queryEntityByEId(QueryEntityModel model) throws BusinessException, InvocationTargetException, IllegalAccessException {
//        sys_oper：员工表，关联员工头像
//        apply：员工申请表
//        news：新闻表
//        message：消息基表（申请、公告基）
//        company:公司logo功能的时候使用
        String entityTbl = model.getEntityTbl();
        Long entityId = model.getEntityId();
        String sendOperName = null;
        //查询对应的消息表数据  这个方法有可能抛异常，需要数据库中加唯一约束
        Message message = null;
        if(entityTbl.equals("message")){
            message = messageDao.selectById(entityId);
        }else{
            message = messageDao.selectOne(new Message(entityId,entityTbl));
        }
        if(message!=null) {
            Long operId = message.getCreateOperId();
            if (operId != null) {
                Oper oper = operDao.selectById(operId);
                if (oper != null && oper.getOperName() != null) {
                    sendOperName = oper.getOperName();
                }
            }
        }
        Object obj = null;
        switch (entityTbl) {
            case "apply"://我的申请 或 我的审核
//                if (type == null || type != 1 || type != 2) {
//                    return new JsonCommon("404", "entityTbl为申请或审核时，type只能为1或2");
//                }
//                if(type ==1){
//
//                }else{
//
//                }
//                Apply apply = applyService.selectById(entityId);
                Apply apply = null;
                SelectApplyModel selectApplyModel = new SelectApplyModel();
                selectApplyModel.setApplyId(entityId);
                Page page = new Page(model.getPageNum(), model.getPageSize());
                List<Apply> list = applyDao.selectListMapper(selectApplyModel,page);
                if(!list.isEmpty()){
                    apply = list.get(0);
                }
//                log.info("20180224-1:"+apply.getType()+apply.getEId());
                if((apply!=null) && (apply.getType()!=null) && (apply.getType() == 9) && (apply.getEId()!=null)){
//                    log.info("20180224-2");
                    AttRealRecord attRealRecord = attRealRecordDao.selectById(apply.getEId());
                    if(attRealRecord!=null){
                        apply.setRecordTime(attRealRecord.getRecordTime());
                        apply.setAttTime(attRealRecord.getAttTime());
                        Integer timeStatus = attRealRecord.getTimeStatus();
                        Integer addStatus = attRealRecord.getAddStatus();
                        apply.setTimeStatus(timeStatus);
                        apply.setAddStatus(addStatus);
                        if(timeStatus + addStatus  < 5){
                            apply.setAttStatusStr("正常");
                        }else if (timeStatus == 8 && attRealRecord.getRecordType() == 1){
                            apply.setAttStatusStr("迟到");
                        }else if (timeStatus == 8 && attRealRecord.getRecordType() == 2){
                            apply.setAttStatusStr("早退");
                        }else if (timeStatus == 9){
                            apply.setAttStatusStr("未打卡");
                        }else if (timeStatus == 0 && addStatus == 8){
                            apply.setAttStatusStr("地点异常");
                        }
                    }
                }
                apply.setSendOperName(sendOperName);
                obj = apply;
                break;
            case "message"://通知公告
                if(message!=null){
                    message.setSendOperName(sendOperName);
                }
                obj = message;
                break;
            case "conference"://会议
            	obj = conferenceService.selectById(entityId).getData();
//            	SelectConferenceModel selectConferenceModel = new SelectConferenceModel();
//            	selectConferenceModel.setCreateOperId(model.getOperId());
//            	obj = conferenceService.myReceiveConference(selectConferenceModel).getData();
                break;
            case "oper_guest"://访客
            	obj = operGuestDao.selectById(entityId);
                break;
            default:
                throw  new BusinessException("404", "entityTbl:"+ entityTbl +"类型不存在");
        }
        //把消息置为已读 通过operId 和 messId
        Long messId = model.getMessId();
        if(messId!=null){
            messNoticeService.read(model.getMessId(),model.getOperId());
        }
        return obj;
    }
}
